package com.bailugansan.servlet.user;

import com.bailugansan.pojo.User;
import com.bailugansan.service.implement.UserServiceImpl;
import com.bailugansan.util.Constants;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author BailuGansan
 */
public class LoginServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        UserServiceImpl userService = new UserServiceImpl();

        String userCode = req.getParameter("userCode");
        String userPassword = req.getParameter("userPassword");

        User user = userService.login(userCode, userPassword);
        System.out.println(user);
        if(user != null){
            // 给登录成功的用户发放 Session
            req.getSession().setAttribute(Constants.USER_SESSION, user);
            // 重定向，转跳到登录后的页面
            resp.sendRedirect("jsp/frame.jsp");
        } else{
            req.setAttribute("error", "用户名或密码错误");
            req.getRequestDispatcher("login.jsp").forward(req, resp);
        }
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req, resp);
    }
}
